package com.strongbj.iot.devices.amazondb.response.handle;

import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.amazondb.entity.Tag;
import com.strongbj.iot.devices.amazondb.request.message.MQBodyMessage;
import com.strongbj.iot.devices.amazondb.service.MongoDBService;
import com.strongbj.iot.devices.amazonreader.message.ReaderMessage;
import com.strongbj.iot.devices.amazonreader.response.entity.CallLabelEntity;
import com.strongbj.iot.devices.amazonreader.response.entity.CallLabelFactory;
import com.strongbj.iot.devices.amazonreader.response.entity.IEntityFactory;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

class LableKeyReplyHandle implements IMessageHandle<ReaderMessage, Object> {
	private IEntityFactory<List<CallLabelEntity>> labelFactory = new CallLabelFactory();
	private MongoDBService mongoDBSercice = (MongoDBService) ContextUtils.getBean("mongoDBService");
	private static Logger logger = LogManager.getLogger(LableKeyReplyHandle.class.getName());
	private final static String ACTION_CODE_RETURN = "key";
	private static final String TOPIC_NAME = "daio";
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public boolean isHandle(ReaderMessage t) {
		if (t.getType() == 12) {
			return true;
		}
		return false;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ReaderMessage t) {
		byte[] datas = t.getBody(); // 获取从Reader接收到的数据段信息
//		logger.info("收到Reader主动上传的标签信息数据：" + ByteUtil.byteArrToHexString(datas, true));
		List<CallLabelEntity> labs = labelFactory.parse(datas); // 通过简单工厂模式将byte数组转为对象
		logger.info("收到按键的标签信息数据:" + JSON.toJSONString(labs));

		if (labs.size() == 0)
			return null;
		StringBuffer sb = new StringBuffer();
		for (byte b : t.getAddress()) {
			sb.append((b & 0xff) + ".");
		}
		
		String readerCode = sb.toString().substring(0, sb.length() - 1);
		// 保存数据
		for (CallLabelEntity callLabelEntity : labs) {
			Tag tag = mongoDBSercice.findById(callLabelEntity.getLabelId());
			if (tag == null) {
				tag = new Tag();
			}
			tag.setId(callLabelEntity.getLabelId());
			tag.setReaderCode(readerCode);
			tag.setUpdateTime(new Date());
			mongoDBSercice.save(tag);
		}
		
		JSONObject object = new JSONObject();
		object.put("readerCode", readerCode);
		object.put("card", labs.get(0).getLabelId());
		MQBodyMessage<JSONObject> msg = new MQBodyMessage<>();
		msg.setActioncode(ACTION_CODE_RETURN);
		msg.setPostdata(object);
		String json = JSON.toJSONString(msg);
		topicSender.send(TOPIC_NAME, json);
		logger.info("发送标签按键返回信息 JSON={}",json);
		return null;
	}

}
